<?php
namespace lib;
use lib\Curl;
use think\Cache;
class WechatJs{
	public $appid    ='wxd0465d5af41c5968';
	public $AppSecret='3f7c7c50876a032127520f80587b32fa';			//公众号秘钥
	protected $arr=[];
	//获取jssdk初始化数据
	public function js_api_config(){
		$this->create_config_data();
		$arr=$this->arr;
		$arr['appId']=$this->appid;
		return $arr;
	}
	//获取jsAPI临时票据
	public function jsapi_ticket(){
		$jsapi_ticket=Cache::get('jsapi_ticket');
		if(!$jsapi_ticket){
			$rel=$this->get_jsapi_ticket();
			Cache::set('jsapi_ticket',$rel['ticket'],7000);
			return $rel['ticket'];
		}else{
			return $jsapi_ticket;
		}
	}
	//获取jsapi_ticket
	protected function get_jsapi_ticket(){
		$access_token=$this->access_token();
		$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
		$rel=Curl::https_curl($url);
		$rel=json_decode($rel,1);
		return $rel;
	}
	//获取微信全局access_token
	public function access_token(){
		$access_token=Cache::get('access_token');
		if(!$access_token){
			$rel=$this->get_access_token();
//			dump($rel);
			Cache::set('access_token',$rel['access_token'],7000);
			return $rel['access_token'];
		}else{
			return $access_token; 
		}
	}
	//获取access_token及获取时间expires_in
	protected function get_access_token(){
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->AppSecret;
		$rel=Curl::https_curl($url);
		$rel=json_decode($rel,1);
		return $rel;
	}
	//创建jssdk初始化
	public function create_config_data(){
		$url=request()->url(true);
		$arr['url'] 		=$url;
		$arr['jsapi_ticket']=$this->jsapi_ticket();
		$arr['noncestr']	=nonce_str();
		$arr['timestamp']	=time();
		$this->arr=$arr;
		$this->sign();
	}
	//微信jsAPI统一签名
	protected function sign(){
		$arr=$this->arr;
		ksort($arr);
		$buff = "";
		foreach ($arr as $k => $v){
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$stringA = trim($buff, "&");
//		$stringSignTemp=$stringA.'&key='.$this->keyval;
		$sign=sha1($stringA);
		$this->arr['sign']=$sign;
	}
}
